<!DOCTYPE html>
<html>
<head>
<title>subscribe must fail in service worker after permission is reset</title>
<link rel="manifest" href="resources/push_manifest.json">
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="../serviceworker/resources/test-helpers.js"></script>
<script src="../notifications/resources/test-helpers.js"></script>
</head>
<body>
<script>
// This test requires the test runner.
async_test(function(test) {
    if (window.testRunner)
        testRunner.setPermission('push-messaging', 'granted', location.origin, location.origin);

    var script = 'resources/instrumentation-service-worker.js';
    var scope = 'resources/scope/' + location.pathname;
    var registration;
    var port;

    getActiveServiceWorkerWithMessagePort(test, script, scope)
        .then(function(workerInfo) {
            registration = workerInfo.registration;
            port = workerInfo.port;

            // 1. Call subscribe in document context. The manifest details are stored in the service
            // worker storage for later use in a service worker context where there is no manifest.
            return registration.pushManager.subscribe({ userVisibleOnly: true });
        })
        .then(function(subscription) {
            assert_true(subscription instanceof window.PushSubscription);

            // 2. Call unsubscribe so we can subscribe again later inside a service worker.
            return subscription.unsubscribe();
        })
        .then(function(unsubscription_result) {
            assert_true(unsubscription_result,
                        'unsubscribe() on an active subscription should resolve with |true|');

            // 3. Revoke permission.
            if (window.testRunner)
                testRunner.setPermission('push-messaging', 'prompt', location.origin, location.origin);

            // 4. Call subscribe in service worker context. It should now fail because permission
            // was reset to default.
            port.postMessage({command: 'subscribe'});

            port.addEventListener('message', function(event) {
                if (typeof event.data != 'object' || !event.data.command)
                    assert_unreached('Invalid message from the service worker');

                assert_equals(event.data.command, 'subscribe');
                assert_false(event.data.success, 'subscribe must fail after permission is reset');
                assert_regexp_match(event.data.errorMessage, /permission denied/);

                test.done();
            });
        })
        .catch(unreached_rejection(test));
}, 'subscribe must fail in service worker after permission is reset');
</script>
</body>
</html>
